package com.yuexiang.melodyhub.authserver.handler;

import com.yuexiang.melodyhub.authserver.dto.OAuthLogin.param.OAuthLoginParam;
import com.yuexiang.melodyhub.authserver.handler.context.LoginContext;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizCodeConstant;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizConstant;
import com.yuexiang.melodyhub.common.exception.RequestArgumentException;
import com.yuexiang.melodyhub.common.handler.AbstractValidationHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class CaptchaValidationHandler extends AbstractValidationHandler<LoginContext> {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void handler(LoginContext content) {
        OAuthLoginParam param = content.getOAuthLoginParam();
        String cacheCode = (String) redisTemplate.opsForHash().get(BizConstant.CAPTCHA_KEY, param.getKaptchaKey());
        if (!StringUtils.hasLength(cacheCode) || !cacheCode.replace("\"", "").equals(param.getCaptchaCode()))
            throw new RequestArgumentException(BizCodeConstant.Msg.CODE_IS_INVALID);
        handlerNext(content);
    }
}
